#include "RtspDecodeThread.h"
#include <unistd.h>

RtspDecodeThread::RtspDecodeThread(RunConfig& con_data,QObject *parent)
    : QThread(parent)
    , data_t(con_data)
    , soft_decode(new RtspDecodeSoft())
    , isRunning(true)
{ 

}
RtspDecodeThread::~RtspDecodeThread()
{
    delete soft_decode;
}
//开启解码线程
void RtspDecodeThread::startDecoding()
{
    if (!soft_decode)
        return;
    isRunning = true;
    start(); // 启动线程
}
//关闭解码线程
void RtspDecodeThread::stopDecoding()
{
    if (!soft_decode)
        return;

    isRunning = false;
    wait(); // 等待线程结束
}
//启动显示
void RtspDecodeThread::start_Display_signal(void){
    isRunning = true;
}
//停止显示
void RtspDecodeThread::stop_Display_signal(void){
    isRunning = false;
}
//线程主循环(不可直接调用)
void RtspDecodeThread::run()
{
    bool ret_t;
    //确认解码器不为空
    if (!soft_decode){
        return;
    }

    if (pingIP(data_t.getString("ipc_ip","10.222.222.150")) == 0)
    {
        /* IP不存在 */
        emit pop_warning(1);
        while (1)
        {
            sleep(1);
            if (pingIP(data_t.getString("ipc_ip","10.222.222.150")) == 1)
            {
                std::cout << "摄像头已检测到~~\n";
                break;
            }
        }
    }

    //打开流(只要IP存在，默认可以打开流)
    if (soft_decode->open(data_t.getString("ipc_rtsp_url","rtsp://admin:Fx123456@10.222.222.150:554/cam/realmonitor?channel=1&subtype=0")) == false)
    {
        emit pop_warning(2);
        soft_decode->close();
        while (1)
        {
            sleep(1);
            if (soft_decode->open(data_t.getString("ipc_rtsp_url","rtsp://admin:Fx123456@10.222.222.150:554/cam/realmonitor?channel=1&subtype=0")) == true)
            {
                std::cout << "视频流已检测到~~\n";
                break;
            }else{
                soft_decode->close();//关闭
            }
        }
    }
    

    
    AVPacket packet;
    av_init_packet(&packet);

    // 转换图像格式并发出信号(使用QImage来接收sws_scale函数的输出)
    QImage rgbFrame;
    while (1)
    {
        // while (isRunning)
        {
            // 解封装一帧数据到 packet 中
            if (!soft_decode->decode_one_packet(&packet)) {
                qDebug() << "Failed to decode one packet";
                break;
            }

            soft_decode->decode_one_frame_toQImage(&packet,rgbFrame);//解码一帧数据返回

            emit frameDecoded(rgbFrame); // 发送信号显示

            // 释放 packet，准备下一轮循环
            av_packet_unref(&packet);
        }
    }
    av_packet_unref(&packet);
    soft_decode->close();
}

int pingIP(const std::string& ipAddress) {
    std::string command = "ping -c 1 " + ipAddress; // 使用ping命令，-c 1表示发送一个数据包
    int ret = system(command.c_str()); // 执行命令
    
    if (ret == 0) {
        return 1; // IP存在
    } else {
        return 0; // IP不存在
    }
}